import React from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as kudosAction from '../actions/kudos.action'
import style from './style'
import {Button,IconButton} from 'sq-ui'
import util from '../util'
import { success,Modal,error,Tooltip } from '../ui-components'
import kudoMap from '../constants/kudoMap';
import KudoItem from '../containers/home/KudoItem';

import cx from 'classnames'

@connect(({kudos}) => ({kudos}), dispatch => ({actions: bindActionCreators({...kudosAction }, dispatch)}))
class KudosSettings extends React.Component {
  constructor(props) {
    super(props);
    this.displayName = 'KudosSettings';
    const {
      rewards,
      medal
    } = this.props.kudos;
    this.state = {
      submited: false,
      personalList: medal.personalRewardMedalVOs || [],
      teamList: medal.teamRewardMedalVOs || [],
      personalQuota: rewards.personalQuota || 0,
      teamQuota: rewards.teamQuota || 0,
      isShowModal: false,
      selectIndex: -1,
      selectType: -1,
      selectValue: -1,
    }
  }
  componentDidMount() {
    this.props.actions.fetchRewards(); 
    this.props.actions.fetchMedal();
  }
  componentWillReceiveProps(nextProps) {
    const {
      rewards: nextRewards,
      medal: nextMedal
    } = nextProps.kudos;
    const {
      rewards,
      medal
    } = this.props.kudos;
    if(!!nextRewards && !util.isShallowEqual(rewards, nextRewards)){
      this.setState({
        personalQuota: nextRewards.personalQuota,
        teamQuota: nextRewards.teamQuota,
      });
    }
    if(!!nextMedal && !util.isShallowEqual(medal, nextMedal)){
      this.setState({
        personalList: nextMedal.personalRewardMedalVOs || [],
        teamList: nextMedal.teamRewardMedalVOs || [],
      });
    }
  }
  onFieldChange = (name, value) => {
    if(value.match(/^[0-9]*$/)){
      this.setState({
        [name]: value,
      });
    }
  }
  successInfo = () => {
    success('更新成功');
  }
  getData = (v) => {
    if(v.type === 'update') return v;
    else if(v.type === 'del') return {
      medalType: v.medalType,
      rewardMedalId: v.rewardMedalId,
      orgId: v.orgId,
    };
    else return {
      medalType: v.medalType,
      medalIcon: v.medalIcon,
      medalName: v.medalName,
      description: v.description,
    };
  }
  onSubmit = () => {
    const {
      personalList,
      teamList,
    } = this.state;
    if([...personalList, ...teamList].find(v => v.type !== 'del' && (!v.medalName || !v.description || !v.medalIcon))){
      this.setState({
        submited: true,
      });
      return;
    }
    this.setState({
        submited: false,
      });
    if(!personalList.length){
      return error('请至少添加一种个人勋章');
    }else if(!teamList.length){
      return error('请至少添加一种团队勋章');
    }
    const addPersonalList = personalList.filter(v => v.type === 'add');
    const updatePersonalList = personalList.filter(v => v.type === 'update');
    const delPersonalList = personalList.filter(v => v.type === 'del' && v.rewardMedalId);
    const addTeamList = teamList.filter(v => v.type === 'add');
    const updateTeamlList = teamList.filter(v => v.type === 'update');
    const delTeamlList = teamList.filter(v => v.type === 'del' && v.rewardMedalId);
    this.props.actions.updateRewards({
      personalQuota: +this.state.personalQuota,
      teamQuota: +this.state.teamQuota,
    },()=>{
      this.props.actions.fetchRewards();
      this.successInfo();
    }); 

    if(addPersonalList.length || addTeamList.length){
      this.props.actions.addMedal({
        personalRewardMedalVOs: addPersonalList.map(v => this.getData(v)),
        teamRewardMedalVOs: addTeamList.map(v => this.getData(v)),
      }, () => {
        this.props.actions.fetchMedal();
      })
    }

    if(updatePersonalList.length || updateTeamlList.length){
      this.props.actions.updateMedal({
        personalRewardMedalVOs: updatePersonalList.map(v => this.getData(v)),
        teamRewardMedalVOs: updateTeamlList.map(v => this.getData(v)),
      }, () => {
        this.props.actions.fetchMedal();
      })
    }

    if(delPersonalList.length || delTeamlList.length){
      this.props.actions.delMedal({
        personalRewardMedalVOs: delPersonalList.map(v => this.getData(v)),
        teamRewardMedalVOs: delTeamlList.map(v => this.getData(v)),
      }, () => {
        this.props.actions.fetchMedal();
      })
    }



    /*this.props.actions.updateRewards({
      personalQuota: +this.state.personalQuota,
      teamQuota: +this.state.teamQuota,
    },()=>{
      this.props.actions.fetchRewards();
      this.successInfo();
    }); 

    this.props.actions.addMedal({
      personalRewardMedalVOs: personalList.map(v => {return {
        medalType: v.medalType,
        medalIcon: v.medalIcon,
        medalName: v.medalName,
        description: v.description,
      }}),
      teamRewardMedalVOs: teamList.map(v => {return {
        medalType: v.medalType,
        medalIcon: v.medalIcon,
        medalName: v.medalName,
        description: v.description,
      }}),
    }, () => {
      this.props.actions.fetchMedal();
    })*/
  }
  addRow = (type) => {
    //if(!!this.state.addList.filter(v => v.medalType === type).find(v => !v.medalName)) return;
    
    this.setState({
      [type === 0 ? 'personalList' : 'teamList']: [
        ...this.state[type === 0 ? 'personalList' : 'teamList'],
        {
          medalType: type,
          medalIcon: '',
          medalName: '',
          description: '',
          type: 'add',
          isDeletable: true,
        }
      ]
    });
  }
  showModal = (i, type) => {
    this.setState({
      selectIndex: i,
      selectType: type,
      isShowModal: true,
    });
  } 
  onHide = () => {
    this.setState({
      selectIndex: -1,
      selectType: -1,
      selectValue: -1,
      isShowModal: false,
    });
  }
  selectIcon = (v) => {
    this.setState({
      selectValue: v,
    })
  }
  handleSubmit = () => {
    const {
      selectIndex,
      selectType,
      selectValue,
    } = this.state;
    this.onRowChange(selectIndex, 'medalIcon', selectValue, selectType);
    this.onHide();
  }
  renderItem = (i, v, type, disabled) => {  
    if(v.type === 'del') return null;
    return (
      <div key={i} className={style['kudo-item']}>
        <Tooltip tip={'点击更换图标'} arrow={'top'} className={style['tip']}>
          <div className={cx({
            [style['img']]: true,
            [style['active']]: !!v.medalIcon,
          })} onClick={this.showModal.bind(this, i, type)}>{v.medalIcon ? <img src={v.medalIcon} /> : null}</div>
        </Tooltip>
        <input 
          value={v.medalName}
          className={style['name']}
          onChange={e => {this.onRowChange(i,'medalName',e.target.value,type)}}
        />
        <input 
          className={style['des']}
          value={v.description}
          onChange={e => {this.onRowChange(i,'description',e.target.value,type)}}
        />
        {
          disabled && !!v.isDeletable ?
          <IconButton
            style={{ cursor: 'pointer' }}
            size="16"
            icon="delete"
            onClick={this.handleDelete.bind(this,i,type)}
          />
          : null
        }
        
        <span className={style['error']}>{this.state.submited&&(!v.medalName || !v.description || !v.medalIcon)? '请填写完整' : ''}</span>
      </div>
    );
  }
  onRowChange = (index, name, value, type) => {
    this.setState({
      [type === 0 ? 'personalList' : 'teamList']
        : this.state[type === 0 ? 'personalList' : 'teamList'].map((v, i) => {
          if(i === index){
            return {
              ...v,
              [name]: value,
              type: v.type === 'add' ? 'add' : 'update',
            }
          }else return v;
        })
    });
  }
  handleDelete = (index, type) => {
    this.setState({
      [type === 0 ? 'personalList' : 'teamList']
        : this.state[type === 0 ? 'personalList' : 'teamList'].map((v, i) => {
          if(i === index){
            return {
              ...v,
              type: 'del',
            }
          }else return v;
        })
    });
  }
  render() {
    const {
      personalList,
      teamList
    } = this.state;
    const personalDisabled = personalList.filter(v => v.type !== 'del').length !== 1;
    const teamDisabled = teamList.filter(v => v.type !== 'del').length !== 1;
    return (
      <div className={style['container-layout']} style={{width:'684px'}}>
        <div className={style['container-title']}>赞赏限额</div>
        <div className={style['remind-item']}>
          <span className={style['remind-span']}>每人每月可发个人赞赏：</span>
          <div className={style['remind-area']}>
            <input 
              value={this.state.personalQuota}
              onChange={e => {this.onFieldChange('personalQuota',e.target.value)}}
            />
            个</div>
        </div>
        <div className={style['remind-item']}>
          <span className={style['remind-span']}>每人每月可发团队赞赏：</span>
          <div className={style['remind-area']}>
            <input 
              value={this.state.teamQuota}
              onChange={e => {this.onFieldChange('teamQuota',e.target.value)}}
            />
            个</div>
        </div>
        <div style={{marginTop: '40px'}} className={style['container-title']}>个人勋章管理</div>
        {
          personalList.map((v, i) => {
            return this.renderItem(i, v, 0, personalDisabled);
          })
        }
        <Button blueLine label={'添加'} style={{height: '35px'}} onClick={this.addRow.bind(this, 0)} />
        <div style={{marginTop: '40px'}} className={style['container-title']}>团队勋章管理</div>
        {
          teamList.map((v, i) => {
            return this.renderItem(i, v, 1 ,teamDisabled);
          })
        }
        <Button blueLine label={'添加'} style={{height: '35px'}} onClick={this.addRow.bind(this, 1)} />
        <div style={{height: '45px',marginTop:'60px'}}>
          <Button  style={{ width: '130px',float:'right', height: '45px', marginTop: '15px',fontSize:'14px' }} blue label="更新" onClick={this.onSubmit} />
        </div>
        <Modal
          active={this.state.isShowModal}
          onRequestClose={this.onHide}
          actions={['cancel', this.handleSubmit ]}
          title="选择勋章"
        >
          <div className={style['kudo-box']}>
            {
              kudoMap.map((v, i) => {
                const flag = ~[...personalList, ...teamList].findIndex(item => item.medalIcon === v);
                return (
                  <div className={cx({
                    [style['icon-item']]: true,
                    [style['active']]: v === this.state.selectValue,
                    [style['disabled']]: flag,
                  })}
                    onClick={() => { if(!flag) this.selectIcon(v) }}
                  ><img src={v}/></div>
                );
              })
            }
          </div>
        </Modal>
      </div>
    );
  }
}

export default KudosSettings;
